package cn.com.czpb.client.module.live;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.BaseFragment;
import cn.com.czpb.client.custorm.TopPicViewPager;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.live.LiveItemBean;
import cn.com.czpb.client.model.live.LiveListEntity;
import cn.com.czpb.client.module.MainActivity;
import cn.com.czpb.client.module.live.adapter.LiveRecycleAdapter;
import cn.com.czpb.client.module.live.adapter.TopviewpagerLiveAdapter;
import cn.com.czpb.client.module.live.view.TopViewLive;
import cn.com.czpb.client.module.live.view.TopViewPagerLIveView;
import cn.com.czpb.client.module.video.utils.VideoPlayerHelper;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import me.relex.circleindicator.CircleIndicator;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/10/18.
 */

public class LiveFragment extends BaseFragment implements OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener, View.OnClickListener {

    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.mrecyclerview)
    RecyclerView mRecyclerView;
//    @BindView(R.id.ll_pic_txt)
    LinearLayout llPicTxt;
//    @BindView(R.id.ll_video)
    LinearLayout llVideo;
    TextView tv_title_id;
    Unbinder unbinder;
    private TopViewPagerLIveView topViewPagerView;
    private TopViewLive topViewlive;
    private LiveRecycleAdapter adapter;
    private Boolean isFirstLoadFlash = true;

    private int page = 1;
    private static final int pageSize = 15;//
    private boolean mFlagRefresh = true;
    private LoginQuitBR br;
    //---------------------------------------------------------------------
//    @BindView(R.id.test_pager)
    TopPicViewPager testPager;//viewpager
//    @BindView(R.id.indicator)
    CircleIndicator mGuideIndicator;
    private Handler viewHandler = new Handler();
    private MyRun switchTask;//切换线程
    private boolean isContinue = true;//是否可以自动切换
    private TopviewpagerLiveAdapter topAdapter;
    private int interval = 4;//播放间隔时间
    //---------------------------------------------------------------------


    public static LiveFragment newInstance() {
        LiveFragment liveFragment = new LiveFragment();
        return liveFragment;
    }

    @Override
    public int setMyContentView() {
        return R.layout.fragment_livening;
    }

    @Override
    public void initView() {
        topViewlive = TopViewLive.instance(activity);
        testPager = topViewlive.getView().findViewById(R.id.test_pager);
        mGuideIndicator = topViewlive.getView().findViewById(R.id.indicator);
        llPicTxt = topViewlive.getView().findViewById(R.id.ll_pic_txt);
        llVideo = topViewlive.getView().findViewById(R.id.ll_video);
        tv_title_id = topViewlive.getView().findViewById(R.id.tv_title_id);
        llPicTxt.setOnClickListener(this);
        llVideo.setOnClickListener(this);
        //初始化swip

        refresh.setRefreshHeader(new ClassHeader_other(activity));
        refresh.setOnRefreshListener(this);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        initAdapter();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    /**
     * adapter init
     */
    private void initAdapter() {
        adapter = new LiveRecycleAdapter(null, spu.getShowImage());
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mRecyclerView.setAdapter(adapter);
        topAdapter = new TopviewpagerLiveAdapter(activity);
        adapter.addHeaderView(topViewlive.getView());
        testPager.setAdapter(topAdapter);
        viewHandler.removeCallbacksAndMessages(null);
        switchTask = new MyRun();
        testPager.setCurrentItem(0);
        testPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == topAdapter.getCount() - 1) {
//                    testPager.setCurrentItem(1, false);
                    testPager.setCurrentItem(topAdapter.getCount() - 1, false);
                    tv_title_id.setText(topAdapter.getBean(position).getTitle());
                    return;
                } else if (0 == position) {
//                    testPager.setCurrentItem(topAdapter.getCount() - 2, false);
                    testPager.setCurrentItem(0, false);
                }
                tv_title_id.setText(topAdapter.getBean(position).getTitle());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        getFlash();
    }

    @Override
    public void initData() {
        //首次进入 延迟刷新
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                mFlagRefresh = true;
                showDialog_index();
                getActiveListData();
                getFlash();
            }
        }, 200);
    }

    /**
     * 获取视频列表数据
     */
    private void getActiveListData() {
        Map<String, String> map = new HashMap();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
        map.put("device", DeviceUtils.getMyUUID(activity));
        LogUtils.i("device-->" + DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().liveList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveListEntity>() {
                    @Override
                    public void call(LiveListEntity entity) {
                        disMissDialog_index();
                        setListData(entity.data);
                        refresh.finishRefresh();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("异常-->" + throwable.toString());
                        adapter.loadMoreFail();
                    }
                });
    }

    public void setListData(List<LiveItemBean> list) {

        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < pageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
        refresh.setEnabled(true);


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            VideoPlayerHelper.getInstance().stop();
        }
    }
    private void getFlash() {
        LogUtils.i("init", "getflash");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", "135");
        map.put("device", DeviceUtils.getMyUUID(activity));
        if (spu.getUser()!=null){
            map.put("uid",spu.getUser().getUid());
        }
        map.put("uid", "135");
        Factory.provideHttpService()
                .liveFlashList(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LiveListEntity, Boolean>() {
                    @Override
                    public Boolean call(LiveListEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveListEntity>() {
                               @Override
                               public void call(LiveListEntity entity) {
                                   if (isFirstLoadFlash) {
                                       LogUtils.i("flash--200-->成功-first");
                                       reFreshFlashData(entity.data);
//                                       if (isFirstLoadFlash) {
//                                           topViewPagerView = TopViewPagerLIveView.instance(activity);
//                                           isFirstLoadFlash = false;
////
//                                           isFirstLoadFlash = false;
//                                           adapter.addHeaderView(topViewPagerView.getView(),0);
////                                           adapter.addHeaderView(topViewlive.getView(),1);
//                                           topViewPagerView.reFreshFlashData(entity.data);
//                                       } else {
//                                           topViewPagerView.reFreshFlashData(entity.data);
//                                       }
                                   }
                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {

                                   LogUtils.i("flash--200-->失败" + throwable.toString());
                               }
                           }
                );
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        LiveItemBean itemBean = (LiveItemBean) adapter.getItem(position);
        switch (view.getId()) {

            case R.id.rl_id:

                PageCtrl.start2LiveDetailActivity(activity, itemBean);
                break;
        }
    }

    private int mCurrentCounter = 0;
    private static final int TOTAL_COUNTER = 18;
    private boolean isErr;
    private boolean mLoadMoreEndGone = false;

    @Override
    public void onLoadMoreRequested() {
        refresh.setEnabled(false);
        mFlagRefresh = false;
        page++;
        showDialog_index();
        getActiveListData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        br = new LoginQuitBR();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.SHOW);
        filter.addAction(MainActivity.UNSHOW);
        activity.registerReceiver(br, filter);
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(br != null) {
            activity.unregisterReceiver(br);
        }
        unbinder.unbind();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_pic_txt:
                PageCtrl.start2LiveListActivity(activity,"1");
                break;
            case R.id.ll_video:
                PageCtrl.start2LiveListActivity(activity,"2");
                break;
        }
    }

    public class LoginQuitBR extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MainActivity.SHOW)) {
                adapter.notifyDataSetChanged();
            } else if (action.equals(MainActivity.UNSHOW)) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                mFlagRefresh = true;
                showDialog_index();
                getActiveListData();
            }
        }, 2000);
    }


    /**
     * 轮播定时滚动
     */
    /**
     * 轮播定时滚动
     */
    class MyRun implements Runnable {
        private boolean isStart = false;

        public void run() {
            try {
                if (isContinue && isStart) {

                    int current = testPager.getCurrentItem();
                    int total = testPager.getAdapter().getCount();
                    if (total == current + 1) {
                        testPager.setCurrentItem(0, false);
                    } else {
                        testPager.setCurrentItem(current + 1, true);
                    }
                } else {
                    isStart = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            viewHandler.postDelayed(switchTask, interval * 1000);
        }
    }

    public void reFreshFlashData(List<LiveItemBean> mViewPagelist) {
        topAdapter.setData(mViewPagelist);
        mGuideIndicator.setViewPager(testPager);
        if (mViewPagelist.size() > 1) {
            testPager.setCurrentItem(0, false);
        }
        tv_title_id.setText(topAdapter.getBean(0).getTitle());
        if (topAdapter.getListSize() > 1) {
            if (switchTask.isStart) {
                viewHandler.removeCallbacks(switchTask);
            }
            switchTask.run();
        }
    }

}
